class ChatController < ApplicationController
  before_filter :user_authorize
  layout "index",:except => [:getMessage,:sendMessage,:index]
  def index
    
  end
  
  def sendMessage
    begin
      chatcontent = ChatContent.new
      chatcontent.chat_from=params[:userid]
      chatcontent.chat_from_name=session[:user_name]
      if params[:chatto]=="undefined"
        chatcontent.chat_to="ALL"
      else
        results = ActiveSupport::JSON.decode(params[:chatto].to_s)
        ids="|"
        results.each do |result|
          ids << result["id"]+"|"
        end
        chatcontent.chat_to=ids
      end
      if params[:chattoname]=="undefined"
        chatcontent.chat_to_name="所有人"
      else
        results = ActiveSupport::JSON.decode(params[:chattoname].to_s)
        names=""
        results.each do |result|
          names << result["id"]+","
        end
        names = names[0,names.length-1]
        chatcontent.chat_to_name=names
      end
      
      chatcontent.content=params[:content]+"<br>"
      chatcontent.save
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  def getMessage
    begin
      
      #@chatcontents = ChatContent.find(:all,:order => "id desc",:limit => 20)
      @chatcontents = ChatContent.find(:all,:conditions=>["chat_to like ? OR chat_from = ? OR chat_to = ?","%|"+session[:user_id].to_s+"|%",session[:user_id],"ALL"],:limit => 30)
      #@chatcontents.each do |chatcontent|
        #page.insert_html :bottom, :chat_contents, chatcontent.content
        #page["chat_contents"].insert_html chatcontent.content
      #end
      respond_to do |format|
        format.html
        format.js
      end
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  #得到某用户的消息ID
  def getLastMsgID
    begin
      id = 0
      chatcontents = ChatContent.find(:last,:conditions=>["chat_to like ? OR chat_to = ?","%|"+session[:user_id].to_s+"|%","ALL"],:select=>'id')
      id = chatcontents.id if chatcontents
      if id.to_i > session[:latest_chat_id].to_i
        #如果ID相差在10以上时,保存一次数据库
        User.update_all("latest_chat_id = #{id}","id = #{session[:user_id]}")
        session[:latest_chat_id] = id
      end
      render :text=>id, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
end
